package cn.yunbamboos.rest.service.converter;

import cn.yunbamboos.rest.service.dto.out.GenericOutDTO;
import cn.yunbamboos.rest.service.logs.LogMetadataThreadLocal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.lang.Nullable;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class GenericOutDTOToHttpMessageConverter extends DTOToHttpMessageConverter<GenericOutDTO> {

    private static final Logger logger = LoggerFactory.getLogger(GenericOutDTOToHttpMessageConverter.class);

    public GenericOutDTOToHttpMessageConverter() {
        super(MediaType.APPLICATION_JSON);
    }

    @Override
    public boolean canRead(Class<?> clazz, @Nullable MediaType mediaType) {
        boolean result = GenericOutDTO.class.isAssignableFrom(clazz);
        if (logger.isTraceEnabled()) {
            logger.trace("read {} {}", result, clazz);
        }
        return result;
    }

    @Override
    public boolean canWrite(Class<?> clazz, @Nullable MediaType mediaType) {
        boolean result = GenericOutDTO.class.isAssignableFrom(clazz);
        if (logger.isTraceEnabled()) {
            logger.trace("write {} {}", result, clazz);
        }
        return result;
    }

    @Override
    public GenericOutDTO read(Class<? extends GenericOutDTO> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        return null;
    }

    @Override
    public void write(GenericOutDTO out, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        String str = out.toJSONString();
        LogMetadataThreadLocal.setCode(out.getCode());
        LogMetadataThreadLocal.setMsg(out.getMsg());
        LogMetadataThreadLocal.setOut(str);
        outputMessage.getBody().write(str.getBytes(StandardCharsets.UTF_8));
    }

}
